package com.snj.visangedu.studytime;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.snj.visangedu.HomeActivity;
import com.snj.visangedu.R;
import com.snj.visangedu.lib.CustomHttpClient;
import com.snj.visangedu.lib.Global;
import com.snj.visangedu.lib.SV_Chronometer;

public class StopwatchFragment extends Fragment implements OnClickListener {
	private final String TAG = "StopwatchFragment";
	
	
	int[] arr_num_b = new int[10];
	ArrayList<StopwatchItem> mList_Stopwatch = new ArrayList<StopwatchItem>();
	StopwatchAdapter _adapter = null;
	
	LinearLayout lily_submenu = null;
	
	ImageView img_h10 = null, img_h1 = null;
	ImageView img_m10 = null, img_m1 = null;
	ImageView img_s10 = null, img_s1 = null;
	ImageView img_ms = null;
	
	ImageView img_hdiv = null, img_mdiv = null, img_spoint = null;
	
	ImageView img_hour = null, img_minute = null, img_sec = null;
	
	ImageView img_edumax = null;
	ImageView img_elapsedtime = null;
	ImageView img_start_stop = null;
	ImageView img_resume = null;
	ImageView img_init = null;
	
	ImageView img_off = null;
	ImageView img_bell = null;
	ImageView img_mute = null;
	
	SV_Chronometer cm = null;
	
	ListView lstv_record = null;
	
	
	LinearLayout lily_mainmenu = null;
	
	
	ProgressDialog mDlg = null;
	
		
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View root = inflater.inflate(R.layout.fragment_stopwatch,
				container, false);
		return root;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		Log.d(TAG, "onActivityCreated");
		
		super.onActivityCreated(savedInstanceState);
		init_widget();
	}
	
	private void init_widget() {
		
		arr_num_b[0] = R.drawable.n0_b;	arr_num_b[1] = R.drawable.n1_b;	arr_num_b[2] = R.drawable.n2_b;	arr_num_b[3] = R.drawable.n3_b;
		arr_num_b[4] = R.drawable.n4_b;	arr_num_b[5] = R.drawable.n5_b;	arr_num_b[6] = R.drawable.n6_b;	arr_num_b[7] = R.drawable.n7_b;
		arr_num_b[8] = R.drawable.n8_b;	arr_num_b[9] = R.drawable.n9_b;
		
		
		
		
		View view = getView();
		
		
		img_start_stop = (ImageView)view.findViewById(R.id.img_stopwatch_start);
		img_start_stop.setOnClickListener(this);
		
		/*
		
		img_resume = (ImageView)view.findViewById(R.id.img_stopwatch_mainmenu2);
		img_resume.setOnClickListener(this);
		
		img_init = (ImageView)view.findViewById(R.id.img_stopwatch_mainmenu00);
		img_init.setOnClickListener(this);
		
		img_elapsedtime = (ImageView)view.findViewById(R.id.img_stopwatch_mainmenu05);
		img_elapsedtime.setOnClickListener(this);
		*/
		img_edumax = (ImageView)view.findViewById(R.id.img_stopwatch_edumax);
		img_edumax.setTag("edumax");
		img_edumax.setSelected(false);
		img_edumax.setOnClickListener(this);
		
		img_off = (ImageView)view.findViewById(R.id.img_submenu0);
		img_off.setSelected(true);
		img_off.setOnClickListener(this);
		img_bell = (ImageView)view.findViewById(R.id.img_submenu1);
		img_bell.setOnClickListener(this);
		img_mute = (ImageView)view.findViewById(R.id.img_submenu2);
		img_mute.setOnClickListener(this);
		
		img_h10 = (ImageView)view.findViewById(R.id.img_h10);
		img_h1 = (ImageView)view.findViewById(R.id.img_h1);
		
		img_m10 = (ImageView)view.findViewById(R.id.img_m10);
		img_m1 = (ImageView)view.findViewById(R.id.img_m1);
		
		img_s10 = (ImageView)view.findViewById(R.id.img_s10);
		img_s1 = (ImageView)view.findViewById(R.id.img_s1);
		
		img_ms = (ImageView)view.findViewById(R.id.img_mm);
		
		img_hour = (ImageView)view.findViewById(R.id.img_hour);
		img_minute = (ImageView)view.findViewById(R.id.img_minute);
		img_sec = (ImageView)view.findViewById(R.id.img_second);
		
		
		img_hdiv = (ImageView)view.findViewById(R.id.img_h_div);
		img_mdiv = (ImageView)view.findViewById(R.id.img_m_div);
		img_spoint = (ImageView)view.findViewById(R.id.img_spoint);
		
		lily_submenu = (LinearLayout)view.findViewById(R.id.lily_stopwatch_submenu);
		lily_submenu.setVisibility(View.GONE);

		cm = (SV_Chronometer)view.findViewById(R.id.chronometer1);
		
		lstv_record = (ListView)view.findViewById(R.id.lstv_record);
		
		
		_adapter = new StopwatchAdapter(getActivity(), R.layout.list_stopwatch, mList_Stopwatch, getActivity().getPackageName());
		lstv_record.setAdapter(_adapter);
		
		lstv_record.setDividerHeight(1);  
	}
	
	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onClick(View v) {
		
		Log.d(TAG, "clicked");
		switch(v.getId())
		{
		
		case R.id.img_stopwatch_edumax:
			
			if(Global.ispaid || cm.isRunning() || img_edumax.getTag().toString().equals("init"))
			{
			
				if(img_edumax.getTag().toString().equals("init"))
				{
					lstv_record.setVisibility(View.GONE);
					mList_Stopwatch.clear();
					
					img_h10.setImageResource(R.drawable.n0_g);
					img_h1.setImageResource(R.drawable.n0_g);
	
					img_m10.setImageResource(R.drawable.n0_g);
					img_m1.setImageResource(R.drawable.n0_g);
					
					img_s10.setImageResource(R.drawable.n0_g);
					img_s1.setImageResource(R.drawable.n0_g);
					
					img_ms.setImageResource(R.drawable.n0_g);
	
					
					img_hour.setImageResource(R.drawable.hour_g);
					img_minute.setImageResource(R.drawable.min_g);
					img_sec.setImageResource(R.drawable.sec_g);
					
					
					img_hdiv.setImageResource(R.drawable.divide_point_g);
					img_mdiv.setImageResource(R.drawable.divide_point_g);
					img_spoint.setImageResource(R.drawable.np_g);
					
					img_edumax.setTag("edumax");
					img_edumax.setImageResource(R.drawable.stopwatch_edumax);
					img_edumax.setPadding(0, Global.dpToPx(getActivity(), 7), 0, Global.dpToPx(getActivity(), 7));
					
					img_start_stop.setImageResource(R.drawable.stopwatch_start);
					img_start_stop.setTag("init"); 
				}
				else if(img_edumax.getTag().toString().equals("elapsedtime"))
				{
					
					final long elapsedtime = cm.GetRecentElapsedTime();
					final Date t = new Date(elapsedtime);
					DateFormat formatter = new SimpleDateFormat("HH:mm:ss:S");
					
					
					String dateFormatted = formatter.format(t);
					
					Log.d(TAG, "Check Time : " + dateFormatted);
					mList_Stopwatch.add(0, new StopwatchItem(mList_Stopwatch.size() + 1, SystemClock.elapsedRealtime() - cm.getBase(), cm.GetRecentElapsedTime()));
					_adapter.notifyDataSetChanged();
					cm.TimeCheck();
					
					Thread th = new Thread(new Runnable() {
						
						@Override
						public void run() {
							// TODO Auto-generated method stub
							
							Log.d(TAG, "upload time : " + elapsedtime);
							
							
							ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
							postParameters.add(new BasicNameValuePair("os", "A"));
							postParameters.add(new BasicNameValuePair("naverid", Global.naverid));
							postParameters.add(new BasicNameValuePair("timetype", "stopwatch"));
							postParameters.add(new BasicNameValuePair("studyingtime", String.format("%d", elapsedtime / 1000)));
							
			            	String result = "";
			            	JSONObject resultobject = null;
			            	
			            	try {
								result = CustomHttpClient.executeHttpPost(Global.recordstudytimeurl, postParameters);
								Log.d(TAG, result);
								 
			            	}
			            	catch(Exception e)
			            	{
			            		e.printStackTrace();
			            	}
						}
					});
					
					th.start();
					
					
					lstv_record.setVisibility(View.VISIBLE);
				}
				else if(img_edumax.getTag().toString().equals("edumax"))
				{
					if(lily_submenu.getVisibility() == View.GONE)
					{
						img_edumax.setSelected(true);
						
						lily_submenu.setVisibility(View.VISIBLE);
					}
					else
					{
						img_edumax.setSelected(false);
						lily_submenu.setVisibility(View.GONE);
					}
				}
			}
			else
			{				
				((HomeActivity)getActivity()).open_paywindow("stopwatch");
			}
			break;
		case R.id.img_stopwatch_start:	// 占쏙옙占쌜뱄옙튼
			img_edumax.setSelected(false);
			lily_submenu.setVisibility(View.GONE);
			
			if(!cm.isRunning())
			{
				img_start_stop.setImageResource(R.drawable.stopwatch_stop);
				
				if(img_start_stop.getTag() == null || img_start_stop.getTag().toString().equals("init"))
					cm.setBase(SystemClock.elapsedRealtime());
				cm.TimeCheck();
				cm.start();
				
				//img_edumax.setVisibility(View.GONE);
				//img_elapsedtime.setVisibility(View.VISIBLE);
				
				
				img_edumax.setImageResource(R.drawable.stopwatch_elapsedtime);
				img_edumax.setPadding(0, Global.dpToPx(getActivity(), 13), 0, Global.dpToPx(getActivity(), 13));
				img_edumax.setTag("elapsedtime");
				
				
				img_hour.setImageResource(R.drawable.hour_b);
				img_minute.setImageResource(R.drawable.min_b);
				img_sec.setImageResource(R.drawable.sec_b);
				
				img_hdiv.setImageResource(R.drawable.divide_point_b);
				img_mdiv.setImageResource(R.drawable.divide_point_b);
				img_spoint.setImageResource(R.drawable.np_b);
				
				img_off.setBackgroundResource(R.drawable.stopwatch_btn_back);
				img_bell.setBackgroundResource(R.drawable.stopwatch_btn_back_disable);
				img_mute.setBackgroundResource(R.drawable.stopwatch_btn_back_disable);
				
				
				new AsyncTask<String, Long, String>() {
					
					@Override
					protected String doInBackground(String... params) {
						// TODO Auto-generated method stub
						
						long elapsedMilis = 0;
						
						while(cm.isRunning())
						{
							elapsedMilis = SystemClock.elapsedRealtime() - cm.getBase();
							
							
							publishProgress(elapsedMilis);
							try {
								Thread.sleep(100);
							} catch (InterruptedException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							
						}
						
						return null;
					}

					@Override
					protected void onProgressUpdate(Long... values) {
						// TODO Auto-generated method stub
						super.onProgressUpdate(values);
						
						
						
						int sec = (int)(values[0] / 1000);
						int min = (int)(sec / 60);
						int hour = (int)(min / 60);
						
						min = min % 60;
						sec = sec % 60;
						
						int msec = (int)(values[0] % 1000);
						
						try
						{
						
							img_h1.setImageResource(arr_num_b[hour % 10]);
							img_h10.setImageResource(arr_num_b[(int)(hour / 10)]);
							
							img_m1.setImageResource(arr_num_b[min % 10]);
							img_m10.setImageResource(arr_num_b[(int)(min / 10)]);
							
							img_s1.setImageResource(arr_num_b[sec % 10]);
							img_s10.setImageResource(arr_num_b[(int)(sec / 10)]);
							
							img_ms.setImageResource(getResources().getIdentifier("n" + (int)(msec / 100) + "_b", "drawable", getActivity().getPackageName()));
							//img_ms.setImageResource(arr.getResourceId((int)(msec / 100), -1));
						}
						catch(Exception e)
						{
							e.printStackTrace();
						}
					}
					
				}.execute("");
			}
			else
			{
				//lstv_record.setVisibility(View.GONE);
				//img_edumax.setVisibility(View.GONE);
				//img_elapsedtime.setVisibility(View.GONE);
				
				//img_start_stop.setVisibility(View.GONE);
				
				//img_init.setVisibility(View.VISIBLE);
				//img_resume.setVisibility(View.VISIBLE);
				
				img_edumax.setImageResource(R.drawable.stopwatch_init);
				img_edumax.setPadding(0, Global.dpToPx(getActivity(), 13), 0, Global.dpToPx(getActivity(), 13));
				img_edumax.setTag("init");
				
				img_start_stop.setImageResource(R.drawable.stopwatch_resume);
				img_start_stop.setTag("stop");
				
				img_off.setBackgroundResource(R.drawable.stopwatch_btn_back_disable);
				img_bell.setBackgroundResource(R.drawable.stopwatch_btn_back_disable);
				img_mute.setBackgroundResource(R.drawable.stopwatch_btn_back);
				final long elapsedtime = cm.GetRecentElapsedTime();
				
				Thread th = new Thread(new Runnable() {
					
					@Override
					public void run() {
						// TODO Auto-generated method stub
						
						Log.d(TAG, "upload time : " + elapsedtime);
						
						
						ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
						postParameters.add(new BasicNameValuePair("os", "A"));
						postParameters.add(new BasicNameValuePair("naverid", Global.naverid));
						postParameters.add(new BasicNameValuePair("timetype", "stopwatch"));
						postParameters.add(new BasicNameValuePair("studyingtime", String.format("%d", elapsedtime / 1000)));
						
		            	String result = "";
		            	JSONObject resultobject = null;
		            	
		            	try {
							result = CustomHttpClient.executeHttpPost(Global.recordstudytimeurl, postParameters);
							Log.d(TAG, result);
							 
		            	}
		            	catch(Exception e)
		            	{
		            		e.printStackTrace();
		            	}
					}
				});
				
				th.start();
				
				cm.stop();
				
				
			}
			break;
		case R.id.img_submenu2:
			
			((HomeActivity)getActivity()).PlayMedia(Global.ex_storage + "/visangedu/bf.MS4");
						
			img_mute.setSelected(true);
			img_bell.setSelected(false);
			img_off.setSelected(false);
			break;
		case R.id.img_submenu1:
			
			((HomeActivity)getActivity()).PlayMedia(Global.ex_storage + "/visangedu/bn.MS4");
			
			
			img_mute.setSelected(false);
			img_bell.setSelected(true);
			img_off.setSelected(false);
			break;
		case R.id.img_submenu0:
			((HomeActivity)getActivity()).StopMedia();
			img_mute.setSelected(false);
			img_bell.setSelected(false);
			img_off.setSelected(true);
			break;
		
		}
		
		
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		
		
		
		super.onPause();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		
		((HomeActivity)getActivity()).StopMedia();
		
		if(cm.isRunning())
		{
			final long elapsedtime = cm.GetRecentElapsedTime();
			
			Thread th = new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					
					Log.d(TAG, "upload time : " + elapsedtime);
					
					
					ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
					postParameters.add(new BasicNameValuePair("os", "A"));
					postParameters.add(new BasicNameValuePair("naverid", Global.naverid));
					postParameters.add(new BasicNameValuePair("timetype", "stopwatch"));
					postParameters.add(new BasicNameValuePair("studyingtime", String.format("%d", elapsedtime / 1000)));
					
	            	String result = "";
	            	JSONObject resultobject = null;
	            	
	            	try {
						result = CustomHttpClient.executeHttpPost(Global.recordstudytimeurl, postParameters);
						Log.d(TAG, result);
						 
	            	}
	            	catch(Exception e)
	            	{
	            		e.printStackTrace();
	            	}
				}
			});
			
			th.start();
			
			cm.stop();
		}
		
		super.onDestroy();
		
		
	}
	
	private void startDownload_EdumaxAudio() {
	    String url0 = "http://studyview.co.kr/ms4/bf.MS4";
	    String url1 = "http://studyview.co.kr/ms4/bn.MS4";
	    new AsyncTask<String, String, String>(){
	    	
	    	@Override
	    	protected void onPreExecute() { 
	    		
	    	    mDlg = new ProgressDialog(getActivity());
	    	    mDlg.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	    	    mDlg.setMessage("다운로드 중입니다");
	    	    mDlg.show();
	    	 
	    	    super.onPreExecute();
	    	}

			@Override
			protected String doInBackground(String... params) {
				// TODO Auto-generated method stub
				int count = 0;
			     
			    try {
			    	
			    	for(int i=0; i<2; i++)
			    	{
				        Thread.sleep(10);
				        URL url = new URL(params[i].toString());
				        URLConnection conexion = url.openConnection();
				        conexion.connect();
				        
				        Log.d(TAG, "Download from " + params[i]);
				 
				        int lenghtOfFile = conexion.getContentLength();
				        Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
				 
				        InputStream input = new BufferedInputStream(url.openStream());
				        OutputStream output = new FileOutputStream(Global.ex_storage + "/visangedu/" + (i == 0 ? "bf.MS4" : "bn.MS4"));
				 
				        byte data[] = new byte[1024];
				 
				        long total = 0;
				 
				        while ((count = input.read(data)) != -1) {
				            total += count;
				            
				            
				            publishProgress("progress", "" + (int) ((total * 100) / lenghtOfFile), "" + (i + 1));
				            
				            output.write(data, 0, count);
				        }
				 
				        output.flush();
				        output.close();
				        input.close();
			    	}
			         
			    } catch (InterruptedException e) {
			        e.printStackTrace();
			    } catch (IOException e) {
			        e.printStackTrace();
			    }
			 
			    // 수행이 끝나고 리턴하는 값은 다음에 수행될 onProgressUpdate 의 파라미터가 된다
			    return null;
			}
			
			@Override
			protected void onProgressUpdate(String... progress) {
				
				if (progress[0].equals("progress")) {
			        mDlg.setProgress(Integer.parseInt(progress[1]));
			        mDlg.setMessage("컨텐츠 다운로드 중 : (" + progress[2] + "/2)");
			    } else if (progress[0].equals("max")) {
			        mDlg.setMax(Integer.parseInt(progress[1]));
			    }
			}
			
			@SuppressWarnings("deprecation")
			@Override
			protected void onPostExecute(String result) {
				
				mDlg.dismiss();
				Toast.makeText(getActivity(), "다운로드가 완료되었습니다.", Toast.LENGTH_LONG).show();
							     
			}
	    	
	    }.execute(url0, url1);
	} 
	
}
